package com.geovis.emergency.spd.biz.basic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geovis.emergency.spd.biz.basic.mapper.BasicDutyOrgMapper;
import com.geovis.emergency.spd.biz.basic.service.IBasicDutyOrgService;
import com.geovis.emergency.spd.biz.system.mapper.SystemRoleMapper;
import com.geovis.emergency.spd.cache.SysCache;
import com.geovis.emergency.spd.entity.basic.entity.BasicDutyOrg;
import com.geovis.emergency.spd.entity.basic.pojo.dto.BasicDutyOrgTreeDTO;
import com.geovis.emergency.spd.entity.basic.pojo.vo.BasicDutyOrgVO;
import com.geovis.emergency.spd.entity.system.entity.SystemRole;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 基础模块-组织架构 服务实现类
 * </p>
 *
 * @author Lonsho
 * @version 1.0
 * @date 2022/6/28
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class BasicDutyOrgServiceImpl extends ServiceImpl<BasicDutyOrgMapper, BasicDutyOrg> implements IBasicDutyOrgService {

    private static SystemRoleMapper systemRoleMapper;

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void removeByIdList(Set<String> idList) {
        if (CollUtil.isEmpty(idList)) {
            return;
        }
        //1、刪除本身
        removeByIds(idList);

        //3、刪除孩子节点
        List<BasicDutyOrg> list = baseMapper.selectList(Wrappers.lambdaQuery(BasicDutyOrg.class).select(BasicDutyOrg::getId).in(BasicDutyOrg::getParentId, idList));
        Set<String> childrenIdList = CollUtil.set(false);
        list.forEach(basicDutyOrg -> childrenIdList.add(basicDutyOrg.getId()));
        removeByIdList(childrenIdList);
    }

    @Override
    public List<BasicDutyOrgVO> selectList(BasicDutyOrgTreeDTO search) {
        LambdaQueryWrapper<BasicDutyOrg> queryWrapper = Wrappers.lambdaQuery(BasicDutyOrg.class)
                .like(StrUtil.isNotBlank(search.getOrgName()), BasicDutyOrg::getOrgName, search.getOrgName())
                .like(StrUtil.isNotBlank(search.getFullName()), BasicDutyOrg::getFullName, search.getFullName())
                .orderByAsc(BasicDutyOrg::getParentId)
                .orderByAsc(BasicDutyOrg::getIdx);
        if (ObjectUtil.isNotEmpty(search.getRoleIds())) {
            queryWrapper.and( s -> {
                int i = 0;
                for (String roleId : search.getRoleIds()) {
                    if (i > 0){
                        s.or().apply(StrUtil.format("'{}' = ANY(string_to_array(role_ids,','))", roleId));
                    } else {
                        s.apply(StrUtil.format("'{}' = ANY(string_to_array(role_ids,','))", roleId));
                    }
                    i++;
                }
            });
        }
        List<BasicDutyOrg> selectList = baseMapper.selectList(queryWrapper);
        List<BasicDutyOrgVO> list = selectList.stream()
                .map(s -> {
                    BasicDutyOrgVO basicDutyOrgVO = BeanUtil.toBean(s, BasicDutyOrgVO.class);
                    List<String> rolesName = Lists.newArrayList();
                    if (StrUtil.isNotBlank(basicDutyOrgVO.getRoleIds())){
                        List<String> roleIds = StrUtil.split(basicDutyOrgVO.getRoleIds(), ",");
                        for (String roleId : roleIds) {
                            SystemRole role = SysCache.getRole(roleId);
                            if (ObjectUtil.isNotNull(role)) {
                                rolesName.add(role.getName());
                            }
                        }
                    }
                    if (ObjectUtil.isNotEmpty(rolesName)){
                        basicDutyOrgVO.setRoleNames(StrUtil.join(",",rolesName));
                    }
                    return basicDutyOrgVO;
                })
                .collect(Collectors.toList());
        return  list;
    }
}
